package com.yiwei.ydd.activity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lljjcoder.view.ViewHelper;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.model.LeveListModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.event.LoginSuccessEvent;
import com.yiwei.ydd.fragment.VipLevelUpTipsFragment;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class VipLevelUpTipsActivity extends BaseActivity {


    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_recharge)
    TextView txtRecharge;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.view_total)
    View viewTotal;
    @BindView(R.id.view_progress)
    View viewProgress;
    @BindView(R.id.view_one)
    ImageView viewOne;
    @BindView(R.id.view_two)
    ImageView viewTwo;
    @BindView(R.id.view_three)
    ImageView viewThree;
    @BindView(R.id.txt_one)
    TextView txtOne;
    @BindView(R.id.txt_two)
    TextView txtTwo;
    @BindView(R.id.txt_three)
    TextView txtThree;
    @BindView(R.id.layout_change)
    LinearLayout layoutChange;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    private int selectPoi = 0;
    private Unbinder unbiner;
    private VipLevelUpTipsFragment fragment1;
    private VipLevelUpTipsFragment fragment2;
    private VipLevelUpTipsFragment fragment3;
    private ArrayList<LeveListModel.DatasBean> totalData;
    private int totalWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_level_up_tips);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        getLevelList();
        EventBus.getDefault().register(this);
    }

    private void init() {
        pager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.x10));
        Fragment[] fragments = new Fragment[3];
        fragment1 = new VipLevelUpTipsFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putInt("id", 0);
        fragment1.setArguments(bundle1);
        fragments[0] = fragment1;

        fragment2 = new VipLevelUpTipsFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putInt("id", 1);
        fragment2.setArguments(bundle2);
        fragments[1] = fragment2;

        fragment3 = new VipLevelUpTipsFragment();
        Bundle bundle3 = new Bundle();
        bundle3.putInt("id", 2);
        fragment3.setArguments(bundle3);
        fragments[2] = fragment3;


        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {


            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }
        });

        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            private float mLastOffset;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                int realCurrentPosition;
                int nextPosition;
                float realOffset;
                boolean goingLeft = mLastOffset > positionOffset;

                // If we're going backwards, onPageScrolled receives the last position
                // instead of the current one
                if (goingLeft) {
                    realCurrentPosition = position + 1;
                    nextPosition = position;
                    realOffset = 1 - positionOffset;
                } else {
                    nextPosition = position + 1;
                    realCurrentPosition = position;
                    realOffset = positionOffset;
                }

                // Avoid crash on overscroll
                if (nextPosition > 2
                        || realCurrentPosition > 2) {
                    return;
                }
//                从第一个到第二个
                if (realCurrentPosition == 0 && nextPosition == 1) {
                    ViewHelper.setTranslationX(layoutChange, (totalWidth / 2 * (1 - realOffset)));
                }
//                从第二个到第一个
                if (realCurrentPosition == 1 && nextPosition == 0) {
                    ViewHelper.setTranslationX(layoutChange, (totalWidth / 2 * realOffset));
                }
//                从第二个到第三个
                if (realCurrentPosition == 1 && nextPosition == 2) {
                    ViewHelper.setTranslationX(layoutChange, -(totalWidth / 2 * realOffset));
                }
//                从第三个到第二个
                if (realCurrentPosition == 2 && nextPosition == 1) {
                    ViewHelper.setTranslationX(layoutChange, -(totalWidth / 2 * (1 - realOffset)));
                }
                mLastOffset = positionOffset;
            }

            @Override
            public void onPageSelected(int position) {
                selectPoi = position;
                if (totalData != null) {
                    if (UserInfoGlobal.getUserLevel() == 1) {
                        txtOne.setText(initTextStart("银卡", "当前等级"));
                        txtTwo.setText(initTextStart("金卡", "下一等级"));
                        txtThree.setText(initTextStart("铂金", "最高等级"));
                    } else if (UserInfoGlobal.getUserLevel() == 2) {
                        txtOne.setText(initTextStart("银卡", "已获等级"));
                        txtTwo.setText(initTextStart("金卡", "当前等级"));
                        txtThree.setText(initTextStart("铂金", "最高等级"));
                    } else if (UserInfoGlobal.getUserLevel() == 3) {
                        txtOne.setText(initTextStart("银卡", "已获等级"));
                        txtTwo.setText(initTextStart("金卡", "已获等级"));
                        txtThree.setText(initTextStart("铂金", "当前等级"));
                    }
                    if (position == 0) {
                        fragment1.setLevelInfo(totalData);
                        if (UserInfoGlobal.getUserLevel() == 1) {
                            txtOne.setText(initTextSelect("银卡"));
                        }
                        translationX(0);
                    } else if (position == 1) {
                        fragment2.setLevelInfo(totalData);
                        if (UserInfoGlobal.getUserLevel() == 2) {
                            txtTwo.setText(initTextSelect("金卡"));
                        }
                        translationX(1);
                    } else if (position == 2) {
                        fragment3.setLevelInfo(totalData);
                        if (UserInfoGlobal.getUserLevel() == 3) {
                            txtThree.setText(initTextSelect("铂金"));
                        }
                        translationX(2);
                    }

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        txtOne.post(new Runnable() {
            @Override
            public void run() {
                totalWidth = viewTotal.getWidth();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginSuccessEvent event) {
        getUserInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getUserInfo();
        if (UserInfoGlobal.isLogin()) {
            txtName.setText(UserInfoGlobal.getUserNick());
            Glide.with(this).load(UserInfoGlobal.getUserIcon()).error(R.mipmap.img_default_head).into(imgIcon);
        } else {
            txtName.setText("");
            Glide.with(this).load(R.mipmap.img_default_head).into(imgIcon);
        }
    }

    private void initLevelInfo() {
        if (totalData == null) {
            return;
        }
        Spanned recharge = Spans.with(this).font(UserInfoGlobal.getConsumeMoney(), getResources().getDimensionPixelSize(R.dimen.x48), 0xffFFFFFF).style(Typeface.BOLD).
                font("充值总额(元)", getResources().getDimensionPixelSize(R.dimen.x24), 0xffFFFFFF).
                build();
        txtRecharge.setText(recharge);
//        if (UserInfoGlobal.getUserLevel() == 1) {
//            txtOne.setText(initTextSelect("银卡"));
//        } else if (UserInfoGlobal.getUserLevel() == 2) {
//            txtTwo.setText(initTextSelect("金卡"));
//        } else if (UserInfoGlobal.getUserLevel() == 3) {
//            txtThree.setText(initTextSelect("铂金"));
//        }


        if (UserInfoGlobal.getUserLevel() == 1)

        {
            txtOne.setText(initTextStart("银卡", "当前等级"));
            txtTwo.setText(initTextStart("金卡", "下一等级"));
            txtThree.setText(initTextStart("铂金", "最高等级"));

            viewOne.setImageResource(R.mipmap.img_vip_big);
            setLeftMargin();

            ViewGroup.LayoutParams lp = viewOne.getLayoutParams();
            lp.width = getResources().getDimensionPixelOffset(R.dimen.x70);
            lp.height = getResources().getDimensionPixelOffset(R.dimen.x70);
            viewOne.setLayoutParams(lp);

//            if(Float.valueOf(UserInfoGlobal.getConsumeMoney())>totalData.get(0).)
            ViewGroup.LayoutParams lp1 = viewProgress.getLayoutParams();
            float progress = Float.valueOf(UserInfoGlobal.getConsumeMoney()) / Float.valueOf(totalData.get(1).up_money);
            lp1.width = (int) (totalWidth / 2 * progress);
            viewProgress.setLayoutParams(lp1);
        } else if (UserInfoGlobal.getUserLevel() == 2)

        {
            txtOne.setText(initTextStart("银卡", "已获等级"));
            txtTwo.setText(initTextStart("金卡", "当前等级"));
            txtThree.setText(initTextStart("铂金", "最高等级"));

            viewOne.setImageResource(R.mipmap.img_vip_middle);
            ViewGroup.LayoutParams lp = viewOne.getLayoutParams();
            lp.width = getResources().getDimensionPixelOffset(R.dimen.x42);
            lp.height = getResources().getDimensionPixelOffset(R.dimen.x42);
            viewOne.setLayoutParams(lp);

            viewTwo.setImageResource(R.mipmap.img_vip_big);
            ViewGroup.LayoutParams lp1 = viewTwo.getLayoutParams();
            lp1.width = getResources().getDimensionPixelOffset(R.dimen.x70);
            lp1.height = getResources().getDimensionPixelOffset(R.dimen.x70);
            viewTwo.setLayoutParams(lp1);
            setMiddleMargin();

            if (Float.valueOf(UserInfoGlobal.getConsumeMoney()) <= Float.valueOf(totalData.get(1).up_money)) {
                ViewGroup.LayoutParams lp2 = viewProgress.getLayoutParams();
                lp2.width = (int) (totalWidth / 2);
                viewProgress.setLayoutParams(lp2);
            } else {
                ViewGroup.LayoutParams lp2 = viewProgress.getLayoutParams();
                float progress = Float.valueOf(UserInfoGlobal.getConsumeMoney()) / Float.valueOf(totalData.get(2).up_money);
                lp2.width = (int) (totalWidth * progress);
//                Log.i("dasdaadsdas", "进度" + progress + "宽度" + totalWidth * progress);
                viewProgress.setLayoutParams(lp2);
            }

        } else if (UserInfoGlobal.getUserLevel() == 3)

        {
            txtOne.setText(initTextStart("银卡", "已获等级"));
            txtTwo.setText(initTextStart("金卡", "已获等级"));
            txtThree.setText(initTextStart("铂金", "当前等级"));

            viewOne.setImageResource(R.mipmap.img_vip_middle);
            ViewGroup.LayoutParams lp = viewOne.getLayoutParams();
            lp.width = getResources().getDimensionPixelOffset(R.dimen.x42);
            lp.height = getResources().getDimensionPixelOffset(R.dimen.x42);
            viewOne.setLayoutParams(lp);

            viewTwo.setImageResource(R.mipmap.img_vip_middle);
            ViewGroup.LayoutParams lp1 = viewTwo.getLayoutParams();
            lp1.width = getResources().getDimensionPixelOffset(R.dimen.x42);
            lp1.height = getResources().getDimensionPixelOffset(R.dimen.x42);
            viewTwo.setLayoutParams(lp1);

            viewThree.setImageResource(R.mipmap.img_vip_big);
            setRightMargin();
            ViewGroup.LayoutParams lp2 = viewThree.getLayoutParams();
            lp2.width = getResources().getDimensionPixelOffset(R.dimen.x70);
            lp2.height = getResources().getDimensionPixelOffset(R.dimen.x70);
            viewThree.setLayoutParams(lp2);

//            ViewGroup.LayoutParams lp3 = viewProgress.getLayoutParams();
//
//            viewProgress.setLayoutParams(lp3);
        }


    }

    private void setMiddleMargin() {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) viewTotal.getLayoutParams();
        lp.setMargins(getResources().getDimensionPixelSize(R.dimen.x20), 0, 0, 0);
        viewTotal.setLayoutParams(lp);

        ViewGroup.MarginLayoutParams lp1 = (ViewGroup.MarginLayoutParams) viewProgress.getLayoutParams();
        lp1.setMargins(getResources().getDimensionPixelSize(R.dimen.x20), 0, 0, 0);
        viewProgress.setLayoutParams(lp1);
    }

    private void setLeftMargin() {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) viewTotal.getLayoutParams();
        lp.setMargins(getResources().getDimensionPixelSize(R.dimen.x30), 0, 0, 0);
        viewTotal.setLayoutParams(lp);

        ViewGroup.MarginLayoutParams lp1 = (ViewGroup.MarginLayoutParams) viewProgress.getLayoutParams();
        lp1.setMargins(getResources().getDimensionPixelSize(R.dimen.x30), 0, 0, 0);
        viewProgress.setLayoutParams(lp1);
    }

    private void setRightMargin() {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) viewTotal.getLayoutParams();
        lp.setMargins(getResources().getDimensionPixelSize(R.dimen.x20), 0, getResources().getDimensionPixelSize(R.dimen.x30), 0);
        viewTotal.setLayoutParams(lp);

        ViewGroup.MarginLayoutParams lp1 = (ViewGroup.MarginLayoutParams) viewProgress.getLayoutParams();
        lp1.setMargins(getResources().getDimensionPixelSize(R.dimen.x20), 0, getResources().getDimensionPixelSize(R.dimen.x30), 0);
        lp1.width = (int) (totalWidth-getResources().getDimensionPixelSize(R.dimen.x30));
        viewProgress.setLayoutParams(lp1);
    }


    private Spanned initTextSelect(String one) {
        return Spans.with(this).font(one, getResources().getDimensionPixelSize(R.dimen.x36), 0xffFB5E01).
                build();
    }

    private Spanned initTextStart(String one, String two) {
        return Spans.with(this).font(one, getResources().getDimensionPixelSize(R.dimen.x28), 0xffffffff).
                font("\n" + two, getResources().getDimensionPixelSize(R.dimen.x28), 0x99ffffff).
                build();
    }


    public void getUserInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        Api.api_service.getUserInfo().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus().equals("00")) {
                        UserInfoGlobal.saveUserInfo(result.datas);
                        initLevelInfo();
                        if (selectPoi == 0) {
                            fragment1.setLoginInfo();
                        } else if (selectPoi == 1) {
                            fragment2.setLoginInfo();
                        } else if (selectPoi == 2) {
                            fragment3.setLoginInfo();
                        }
                    } else {

                    }

                });
    }

    public void getLevelList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getLevelList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    totalData = result.datas;
                    initLevelInfo();
                    txtOne.setText(initTextSelect("银卡"));
                    pager.setCurrentItem(UserInfoGlobal.getUserLevel() - 1);
                    translationX(UserInfoGlobal.getUserLevel() - 1);
                    fragment1.setLevelInfo(totalData);
                });
    }

    private void translationX(int poi) {
        if (poi == 0) {
            ViewHelper.setTranslationX(layoutChange, (totalWidth / 2));
        } else if (poi == 1) {
            ViewHelper.setTranslationX(layoutChange, 0);
        } else if (poi == 2) {
            ViewHelper.setTranslationX(layoutChange, -(totalWidth / 2));
        }
    }

    private void translationX(int poi, float progress) {
        if (poi == 0) {
            ViewHelper.setTranslationX(layoutChange, (totalWidth / 2 * progress));
        } else if (poi == 1) {
            ViewHelper.setTranslationX(layoutChange, 0);
        } else if (poi == 2) {
            ViewHelper.setTranslationX(layoutChange, -(totalWidth / 2 * progress));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.view_one, R.id.view_two, R.id.view_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_one:
                pager.setCurrentItem(0);
                translationX(0);
                break;
            case R.id.view_two:
                pager.setCurrentItem(1);
                translationX(1);
                break;
            case R.id.view_three:
                pager.setCurrentItem(2);
                translationX(2);
                break;
        }
    }

    @OnClick({R.id.btn_back, R.id.txt_right})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                if (Util.getIsLogin(this))
                    Util.startActivity(this, VipUpRecordActivity.class);
                break;
        }
    }
}
